﻿using System;

namespace Behaving.Composites
{
    public class BehaviourUtility : INamed
    {
        public BehaviourUtility(Func<float> utilityFunction, Behaviour behaviour = null)
        {
            UtilityFunction = b => utilityFunction();
            Behaviour = behaviour;
        }

        public BehaviourUtility(Func<bool, float> utilityFunction, Behaviour behaviour = null)
        {
            UtilityFunction = utilityFunction;
            Behaviour = behaviour;
        }

        public string Name { get; set; }
        public float ComputedUtility { get; set; }
        public Behaviour Behaviour { get; set; }
        public Func<bool, float> UtilityFunction { get; set; }

        public void ComputeUtility(bool wasLastRunningBehaviour)
        {
            ComputedUtility = UtilityFunction(wasLastRunningBehaviour);
        }

        public BehaviourUtility SetBehaviour(Behaviour behaviour)
        {
            Behaviour = behaviour;
            return this;
        }

        public override string ToString()
        {
            if (!string.IsNullOrWhiteSpace(Name))
            {
                return
                    string.Format(
                        "Behaviour utility {0}: {1}",
                        Name);
            }
            return base.ToString();
        }
    }
}